import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import { getToken,removeToken } from '@/utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from '@/router'

 let apiUrl ='/'
const service = axios.create({
  baseURL: apiUrl,
  timeout: 30000
})
service.interceptors.request.use(
  config => {
    if(config.method=='get'){
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }else{
      config.headers['Content-Type'] = 'application/json'
    }
    NProgress.start()
    if(config.url!='/login')
      config.headers['Authorization'] = 'Bearer '+getToken()
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)
service.interceptors.response.use(
  response => {
    NProgress.done()
    const res = response.data
    if (res?.message?.indexOf('需要登录')>=0) {
      MessageBox.alert('登录验证已过期，请重新登录!', '温馨提示', {
        confirmButtonText: '确定',
        callback: action => {
          removeToken()
          if(localStorage.getItem('menuKey')==9){
            router.push({ path: '/' })
          }else{
            router.push({ path: '/systemLogin' })
          }
        }
      })
      return false
    } else if(res.code==0 || response.status===200) {
      return res
    }else{
      Message({
        message:res.msg || '连接超时!',
        type: 'error',
        duration:3000
      })
      return res
    }
  },
  error => {
    console.log('err' + error)
    Message({
      message: '连接超时!',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

export function getUrl() {
  return  apiUrl
}
export function getSocketUrl() {
    return  'socketUrl'
}

